package com.example.erp.controller;

import static org.springframework.ai.chat.memory.ChatMemory.CONVERSATION_ID;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;

/**
 * 聊天控制器，处理AI聊天请求。
 */
@RestController
@RequestMapping("/api/chat")
public class ChatController {

	@Resource
	private ChatClient chatClient;
	
	/**
	 * 处理聊天请求，使用AI和MCP工具进行响应，postman中测试用
	 *
	 * @param request 聊天请求
	 * @return 包含AI回复的响应
	 */
	@PostMapping("/book")
	public ResponseEntity<com.example.erp.model.ChatResponse> chat(
			@RequestBody com.example.erp.model.ChatRequest request) {
		try {
			// 创建用户消息
			String userMessage = request.getMessage();
			// 使用流式API调用聊天
			String content = chatClient.prompt().user(userMessage).call().content();
			return ResponseEntity.ok(new com.example.erp.model.ChatResponse(content));
		} catch (Exception e) {
			return ResponseEntity.ok(new com.example.erp.model.ChatResponse("处理请求时出错: " + e.getMessage()));
		}
	}

	/**
	 * index.html中测试用
	 * 
	 * @param response
	 * @param id
	 * @param prompt
	 * @return
	 */
	@GetMapping(value = "/book_stream")
	public Flux<ChatResponse> generateStream(HttpServletResponse response, @RequestParam String id,
			@RequestParam String prompt) {
		response.setCharacterEncoding("UTF-8");
		// 配置Advisor参数（对话ID）
		return this.chatClient.prompt(prompt).advisors(advisor -> advisor.param(CONVERSATION_ID, id)).stream().chatResponse();
	}
}
